'use strict';
const {
  Model
} = require('sequelize');
const moment = require('moment');
moment.locale('zh-cn');

module.exports = (sequelize, DataTypes) => {
  class Chapter extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // 关联模型
      models.Chapter.belongsTo(models.Course, { as: 'course' })
    }
  }
  Chapter.init({
    courseId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {
          msg: '课程 ID 必须填写'
        },
        notEmpty: {
          msg: '课程 ID 不能为空'
        },
        async isPresent(value) {
          const course = await sequelize.models.Course.findByPk(value);
          if (!course) {
            throw new Error(`课程ID ${value}不存在`);
          }
        }
      }
    },
    title: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: '章节标题必须填写'
        },
        notEmpty: {
          msg: '章节标题不能为空'
        },
        len: {
          args: [2, 45],
          msg: '章节标题长度必须在2到45个字符之间'
        }
      }
    },
    content: DataTypes.TEXT,
    video: {
      type: DataTypes.STRING,
      validate: {
        isUrl: {
          msg: '视频地址不正确'
        }
      }
    },
    rank: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      defaultValue: 1,
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('createdAt')).format('LL');
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('updatedAt')).format('LL');
      },
    }
  }, {
    sequelize,
    modelName: 'Chapter',
  });
  return Chapter;
};